package com.labor_management_system.Controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.labor_management_system.Entity.Enterprises;
import com.labor_management_system.Entity.LaborEngineering;
import com.labor_management_system.Entity.WorkDetails;
import com.labor_management_system.Service.EnterprisesService;
import com.labor_management_system.Service.LaborEngineeringService;
import com.labor_management_system.Service.WorkDetailsService;
import com.labor_management_system.Utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.IntStream;

@RestController
@RequestMapping("ParticipatingUnits")
public class ParticipatingUnitsController {
    @Autowired
    EnterprisesService enterprisesService;

    @Autowired
    private LaborEngineeringService laborEngineeringService;
    @Autowired
    private WorkDetailsService workDetailsService;
    //参与单位管理
    @PostMapping("/TEST/Gen3")
    public R gen3(){
        IntStream.range(0, 10).forEach(i -> {
            Enterprises enterprise = new Enterprises();
            enterprise.setEnterprisesId(UUID.randomUUID().toString());
            enterprise.setEnterprisesName("Enterprise " + i);
            enterprise.setEnterprisesCategory(new Random().nextInt(5) + 1);
            enterprise.setBusinessCreditCode(generateRandomBusinessCreditCode());
            enterprise.setContact("Contact Person " + i);
            enterprise.setContactPhone("138" + String.format("%08d", new Random().nextInt(100000000)));
            enterprise.setNote("Note " + i);
            enterprise.setLegalRepresentative("Legal Rep " + i);
            enterprise.setPeriodOfBusiness(LocalDate.now().minusDays(new Random().nextInt(365)).toEpochDay());
            enterprise.setProofOfBusiness("Proof " + i);

            enterprisesService.getBaseMapper().insert(enterprise);
        });
        return R.ok();
    }

    private static String generateRandomBusinessCreditCode() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        // 假设营业执照号码由15位数字组成
        for (int i = 0; i < 15; i++) {
            sb.append(random.nextInt(10));
        }

        return sb.toString();
    }
    //新建单位



    @PostMapping("InsertUnit")
    public R InsertUnit(@RequestParam("enterprisesName") String enterprisesName,
                        @RequestParam("enterprisesCategory") Integer enterprisesCategory,
                        @RequestParam("businessCreditCode") String businessCreditCode,
                        @RequestParam("contact") String contact,
                        @RequestParam("contactPhone") String contactPhone,
                        @RequestParam("note") String note,
                        @RequestParam("legalRepresentative") String legalRepresentative,
                        @RequestParam("periodOfBusiness") Long periodOfBusiness,
                        @RequestParam(value = "multipartFile") MultipartFile multipartFile
    ) throws IOException {

        Enterprises enterprises = new Enterprises();
        enterprises.setEnterprisesName(enterprisesName);
        enterprises.setEnterprisesCategory(enterprisesCategory);
        enterprises.setBusinessCreditCode(businessCreditCode);
        enterprises.setContact(contact);
        enterprises.setContactPhone(contactPhone);
        enterprises.setNote(note);
        enterprises.setLegalRepresentative(legalRepresentative);
        enterprises.setPeriodOfBusiness(periodOfBusiness);

        //文件的上传，写入磁盘
        return enterprisesService.upload(enterprises,multipartFile) ? R.ok():R.error().message("文件上传失败");
    }


    //删除单位
    @PostMapping("DeleteUnit")
    public R DeleteUnit(@RequestParam("enterprisesId") String enterprisesId){

        //查询主表的数据
        Enterprises enterprises = enterprisesService.getBaseMapper().selectById(enterprisesId);

        //如果主表数据存在
        if(enterprises !=null){
            //查询关联表的外键数据enterprises_id
            List<LaborEngineering> laborEngineeringList = laborEngineeringService.getBaseMapper().selectList(new QueryWrapper<LaborEngineering>().eq("enterprises_id", enterprisesId));

            //逐一处理关联表的数据
            for(LaborEngineering laborEngineering:laborEngineeringList){
                List<WorkDetails> workDetailsList = workDetailsService.getBaseMapper().selectList(new QueryWrapper<WorkDetails>().eq("labor_engineering_id", laborEngineering.getLaborEngineeringId()));

                //逐一删除第三张表的的外键数据
                for(WorkDetails workDetails:workDetailsList){
                    workDetailsService.getBaseMapper().deleteById(workDetails.getWorkDetailsId());
                }

                // 最后删除关联表的数据
                laborEngineeringService.getBaseMapper().deleteById(laborEngineering.getLaborEngineeringId());
            }

            // 最后删除主表的数据
            enterprisesService.getBaseMapper().deleteById(enterprisesId);

            return R.ok();
        }

        return R.error().message("删除失败");
    }

    //编辑单位
    @PostMapping("UpdateUnit")
    public R UpdateUnit( @RequestParam("enterprisesId") String enterprisesId,
                         @RequestParam("enterprisesName") String enterprisesName,
                         @RequestParam("enterprisesCategory") Integer enterprisesCategory,
                         @RequestParam("businessCreditCode") String businessCreditCode,
                         @RequestParam("contact") String contact,
                         @RequestParam("contactPhone") String contactPhone,
                         @RequestParam("note") String note,
                         @RequestParam("legalRepresentative") String legalRepresentative,
                         @RequestParam("periodOfBusiness") Long periodOfBusiness,
                         @RequestParam(value = "multipartFile",required = false)MultipartFile multipartFile) throws IOException {

        System.out.println("id:"+enterprisesId);

        Enterprises enterprises = new Enterprises();
        enterprises.setEnterprisesName(enterprisesName);
        enterprises.setEnterprisesId(enterprisesId);
        enterprises.setEnterprisesCategory(enterprisesCategory);
        enterprises.setBusinessCreditCode(businessCreditCode);
        enterprises.setContact(contact);
        enterprises.setContactPhone(contactPhone);
        enterprises.setNote(note);
        enterprises.setLegalRepresentative(legalRepresentative);
        enterprises.setPeriodOfBusiness(periodOfBusiness);

        //文件的上传，写入磁盘
        return enterprisesService.updateUnits(enterprises,multipartFile) ? R.ok():R.error().message("文件上传失败");

    }

    //显示所有单位 分页查询
    @PostMapping("ShowAllUnits")
    public R ShowAllUnits(@RequestParam("selectPage") Integer selectPage,@RequestParam("PageSize") Integer PageSize){
        return R.ok().data("UnitInfoList",enterprisesService.showAllUnits(selectPage,PageSize));
    }


    //根据单位名称和单位类别查询
    @PostMapping("findByNameAndCategory")
    public R findByNameAndCategory(@RequestParam("enterprisesName") String enterprisesName,
                                   @RequestParam(value = "enterprisesCategory",required = false) Integer enterprisesCategory){

        return R.ok().data("ListInfoByName",enterprisesService.findByName(enterprisesName,enterprisesCategory));

    }


}
